package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dto.WmMaterialDto;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j//不在类上加事务,所有的方法都会享受事务,哪个方法用,加那个
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.profix}")
    String profix;
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //检测文件是否存在
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文件不存在");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "登录后才能上传文件");
        }
        //上传文件到oss


        try {

            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//截取后缀

            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            String fileUrl = fileStorageService.store(profix, fileName + suffix, multipartFile.getInputStream());
            //创建素材表信息,将图片路径写入
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(fileUrl);
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());

            this.save(wmMaterial);
            //将素材保存到数据困

            //前端调用数据需要加上website前缀
            wmMaterial.setUrl(webSite + fileUrl);

            //封装返回的结果
            return ResponseResult.okResult(wmMaterial);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传出现异常==>{}", e.getMessage());
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败");
        }

    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //检测参数
        dto.checkParam();

        //封装查询条件

        IPage<WmMaterial> pageReq = new Page<>(dto.getPage(),dto.getSize());

        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();

        if (dto.getIsCollection()!=null&&dto.getIsCollection().intValue()==1){//判断不等于null,避免空指针
            queryWrapper.eq(WmMaterial::getIsCollection,1);
        }

        //判读用户是否登录,查询用户的收藏
        WmUser user = WmThreadLocalUtils.getUser();

        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
        }

        queryWrapper.eq(WmMaterial::getUserId,user.getId());

        //按照时间降序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);


        //执行查询
        IPage<WmMaterial> pageResult = this.page(pageReq, queryWrapper);


        List<WmMaterial> resultRecords = pageResult.getRecords();

        if (resultRecords!=null&&resultRecords.size()>0){
            for (WmMaterial resultRecord : resultRecords) {

                resultRecord.setUrl(webSite+resultRecord.getUrl());

            }
        }

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal());

        pageResponseResult.setData(resultRecords);


        return pageResponseResult;
    }

    @Transactional//加事务,删除oss文件出现错误,需要回滚,把素材返回
    @Override
    public ResponseResult delete(Integer id) {


        //判断id是不是为空
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"id不能为空");
        }

        //查询素材数据
        WmMaterial wmMaterial = this.getById(id);

        if (wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该素材不存在");
        }

        //判断是否登录,只能对自己的素材操作

        WmUser user = WmThreadLocalUtils.getUser();

        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (!wmMaterial.getUserId().equals(user.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"无权操作");
        }
        Integer integer = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));

        if (integer>0){

            //存在数据,被引用,不能被删除
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"图片已经被引用,无法被删除");
        }

        this.removeById(id);

        fileStorageService.delete(wmMaterial.getUrl());

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short status) {

        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"id不能为空");
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //修改字段属性,直接用update方法,只能修改本人的收藏

         update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection, status)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, wmUser.getId()));

        return ResponseResult.okResult();
    }
}
